import Medication from '../models/medication.js';
import Result from '../utils/result.js';
import User from '../models/user.js';

const medicationService = {
    async getMedications(userId, allergy) {
        try {
            const user = await User.findOne({
                where: {
                    id: userId,
                },
            });
            if (!user) {
                return Result.error('用户不存在');
            }

            //注意传递过来的allergy为字符串，需要转换为布尔值
            const query = {
                where: {
                    userId: userId,
                },
            };

            if(allergy){
                query.where.allergy = allergy==='true' ? true : false;
            }


            const data = await Medication.findAll(query);

            return Result.success(data, '获得用药记录成功');
        } catch (error) {
            return Result.error(error.message);
        }
    },
    async addMedication(data) {
        try {
            const user = await User.findOne({
                where: {
                    id: data.userId,
                },
            });
            if (!user) {
                return Result.error('用户不存在');
            }
            const result = await Medication.create(data);

            return Result.success(result, '添加用药记录成功').toObject();
        } catch (error) {
            return Result.error(error.message);
        }
    },

    async delMedication(medicationId, userId) {
        try {
            const medication = await Medication.findOne({
                where: {
                    id: medicationId,
                },
            });

            if (!medication) {
                return Result.notfound('用药记录不存在');
            }

            if (userId && medication.userId !== userId) {
                return Result.unauthorized('该用药记录不属于该用户');
            }

            await medication.destroy();
            return Result.success(medicationId, '删除用药记录成功');
        } catch (error) {
            return Result.error(error.message);
        }
    },
};

export default medicationService;
